from flask import Blueprint, jsonify, current_app, request
from backend.config.config_manager import ConfigManager
import logging
from datetime import datetime

config_api = Blueprint('config_api', __name__, url_prefix='/api/config')

@config_api.route('/query-fields', methods=['GET'])
def get_query_area_field_configs():
    """获取主查询区字段配置，供前端FixedQueryArea组件使用"""
    try:
        config_manager = ConfigManager()
        fields = config_manager.get_query_area_field_configs()  # [{field, display_name, input_type, options, ...}, ...]
        logging.warning(f"【调试】接口实际返回 fields: {fields}")
        return jsonify({
            "success": True,
            "fields": fields
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": f"主查询区配置加载失败: {str(e)}"
        }), 500

@config_api.route('/followup_result_fields', methods=['GET'])
def get_followup_result_fields():
    """获取随访模块主表（查询结果表头）配置，供前端动态渲染主表表头和顺序"""
    try:
        config_manager = ConfigManager()
        result = config_manager.build_followup_result_fields()
        return jsonify({
            "success": True,
            "fields": result
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": f"随访主表配置加载失败: {str(e)}"
        }), 500

@config_api.route('/followup_history_fields', methods=['GET'])
def get_followup_history_fields():
    """获取随访历史表格字段顺序和label（全局唯一配置驱动）"""
    try:
        config_manager = ConfigManager()
        result = config_manager.build_followup_history_fields()
        return jsonify({
            "success": True,
            "fields": result
        })
    except ValueError as e:
        import logging
        logging.error(str(e))
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            "success": False,
            "error": f"随访历史表配置加载失败: {str(e)}"
        }), 500

@config_api.route('/student_info_bar_fields', methods=['GET'])
def get_student_info_bar_fields():
    """获取全局唯一学生关键信息栏字段顺序（只返回顺序，属性前端通过全局唯一配置表获取）"""
    try:
        config_manager = ConfigManager()
        fieldsConfig = config_manager.build_student_info_bar_fields()
        return jsonify({
            "success": True,
            "fieldsConfig": fieldsConfig
        })
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            "success": False,
            "error": f"学生关键信息栏配置加载失败: {str(e)}"
        }), 500



@config_api.route('/all_field_config', methods=['GET'])
def get_all_field_config():
    """获取全局唯一字段属性配置表（ALL_FIELD_CONFIG_REGISTRY）"""
    try:
        config_manager = ConfigManager()
        result = config_manager.build_all_field_config_response()
        return jsonify({
            "success": True,
            "data": result
        })
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            "success": False,
            "error": f"全局字段配置加载失败: {str(e)}"
        }), 500

@config_api.route('/followup_form_fields', methods=['GET'])
def get_followup_form_fields():
    """获取随访表单字段配置（全局唯一配置驱动）"""
    try:
        config_manager = ConfigManager()
        result = config_manager.build_followup_form_fields()
        
        return jsonify({
            "success": True,
            "fields": result
        })
        
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            "success": False,
            "error": f"随访表单字段配置加载失败: {str(e)}"
        }), 500

@config_api.route('/followup_validation_rules', methods=['GET'])
def get_followup_validation_rules():
    """获取随访表单验证规则配置"""
    try:
        config_manager = ConfigManager()
        validation_rules = config_manager.get_followup_validation_rules()
        
        return jsonify({
            "success": True,
            "rules": validation_rules
        })
        
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            "success": False,
            "error": f"随访验证规则配置加载失败: {str(e)}"
        }), 500

@config_api.route('/followup_export_config', methods=['GET'])
def get_followup_export_config():
    """获取随访导出配置"""
    try:
        config_manager = ConfigManager()
        export_config = config_manager.get_followup_export_config()
        
        return jsonify({
            "success": True,
            "config": export_config
        })
        
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            "success": False,
            "error": f"随访导出配置加载失败: {str(e)}"
        }), 500

@config_api.route('/search_result_fields/students', methods=['GET'])
def get_unified_student_search_result_fields_config():
    """
    获取全局统一学生查询结果表格字段配置
    
    🔧 重要：这是全局唯一的学生查询结果字段配置，所有模块都应该使用此配置
    用户需求字段：教育id号、学校、年级、班级、姓名、性别、年龄、身份证号码、家长姓名、操作列
    
    📋 使用场景：
    - 视力模块学生查询结果表格
    - 干预模块学生查询结果表格  
    - 随访模块学生查询结果表格
    - 学生档案模块学生查询结果表格
    - 所有需要显示学生列表的场景
    """
    try:
        config_manager = ConfigManager()
        
        # 🔧 全局统一学生查询结果字段（严格按用户需求顺序）
        unified_student_fields = [
            "education_id",    # 教育id号
            "school",          # 学校  
            "grade",           # 年级（来自扩展表）
            "class_name",      # 班级
            "name",            # 姓名
            "gender",          # 性别
            "age",             # 年龄（来自扩展表）
            "id_card",         # 身份证号码
            "parent_name"      # 家长姓名
        ]
        
        fields = []
        
        # 从配置中获取每个字段的完整配置
        for field_name in unified_student_fields:
            field_table = config_manager.get_query_field_table(field_name)
            if field_table:
                # 获取字段所在表的完整配置
                table_fields = config_manager.get_table_fields_config(field_table)
                # 查找当前字段的配置
                field_config = next((f for f in table_fields if f["field"] == field_name), None)
                if field_config:
                    fields.append(field_config)
                else:
                    # 如果在表字段配置中找不到，使用基础配置
                    basic_config = config_manager.get_query_field_config(field_name)
                    if basic_config:
                        fields.append({
                            "field": field_name,
                            "display_name": basic_config.get("display_name", field_name),
                            "input_type": basic_config.get("input_type", "text"),
                            "data_type": basic_config.get("data_type", "varchar"),
                            "table": field_table
                        })
        
        # 全局统一的操作列配置（可通过参数自定义按钮）
        action_field = {
            "field": "actions",
            "display_name": "操作",
            "input_type": "actions",
            "buttons": ["查看", "编辑"]  # 默认操作按钮，模块可覆盖
        }
        fields.append(action_field)
        
        # 同时返回查询列配置
        columns = [field["field"] for field in fields if field["field"] != "actions"]
        columns.extend(["id", "student_id"])  # 添加ID字段和student_id字段用于操作
        
        return jsonify({
            "success": True,
            "fields": fields,
            "columns": columns,
            "description": "全局统一学生查询结果字段配置",
            "usage": "所有模块的学生查询结果表格都应使用此配置"
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": f"全局学生查询结果配置加载失败: {str(e)}"
        }), 500


@config_api.route('/user_profile_editable_fields', methods=['GET'])
def get_user_profile_editable_fields():
    """获取用户资料可编辑字段配置

    目的：前端（含微信小程序）动态渲染用户资料编辑表单，避免硬编码字段；完全遵循全局唯一配置驱动原则。
    返回：
        fields: [ { field, label, type, required?, max_length?, options? } ]
    规则：
        1. 基于 constants_v2.CONFIG_REGISTRY["USER_PROFILE_EDITABLE_FIELDS"].
        2. 若存在 options_source，则从 GLOBAL_OPTIONS_CONFIG[s] 取出 options 列表，注入到返回项的 options 字段。
    """
    try:
        # 延迟导入避免循环引用 & 加速冷启动
        from backend.config import constants_v2
        registry = getattr(constants_v2, 'CONFIG_REGISTRY', {})
        raw_fields = registry.get('USER_PROFILE_EDITABLE_FIELDS', [])
        global_options = registry.get('GLOBAL_OPTIONS_CONFIG', {})
        enriched = []
        for f in raw_fields:
            item = dict(f)
            src = f.get('options_source')
            if src and src in global_options:
                item['options'] = global_options[src]
            enriched.append(item)
        return jsonify({
            'success': True,
            'fields': enriched,
            'timestamp': datetime.utcnow().isoformat() + 'Z'
        })
    except Exception as e:
        logging.exception('获取用户资料可编辑字段失败')
        return jsonify({
            'success': False,
            'error': f'用户资料配置加载失败: {str(e)}'
        }), 500

@config_api.route('/search_result_fields/vision', methods=['GET'])
def get_vision_search_result_fields_config():
    """
    获取视力模块查询结果表格字段配置（向后兼容）
    
    🔧 重要：视力模块应该使用全局统一学生查询结果字段配置
    此端点保留用于向后兼容，但推荐使用 /search_result_fields/students
    """
    try:
        config_manager = ConfigManager()
        
        # 🔧 重定向到全局统一配置，但添加视力模块特定的操作按钮
        # 使用与全局统一配置相同的字段列表
        unified_student_fields = [
            "education_id", "school", "grade", "class_name", 
            "name", "gender", "age", "id_card", "parent_name"
        ]
        
        fields = []
        
        # 从配置中获取每个字段的完整配置
        for field_name in unified_student_fields:
            field_table = config_manager.get_query_field_table(field_name)
            if field_table:
                table_fields = config_manager.get_table_fields_config(field_table)
                field_config = next((f for f in table_fields if f["field"] == field_name), None)
                if field_config:
                    fields.append(field_config)
                else:
                    basic_config = config_manager.get_query_field_config(field_name)
                    if basic_config:
                        fields.append({
                            "field": field_name,
                            "display_name": basic_config.get("display_name", field_name),
                            "input_type": basic_config.get("input_type", "text"),
                            "data_type": basic_config.get("data_type", "varchar"),
                            "table": field_table
                        })
        
        # 视力模块特定的操作列配置
        action_field = {
            "field": "actions",
            "display_name": "操作",
            "input_type": "actions",
            "buttons": ["查询", "录入"]  # 视力模块专用操作按钮
        }
        fields.append(action_field)
        
        columns = [field["field"] for field in fields if field["field"] != "actions"]
        columns.extend(["id", "student_id"])  # 添加 student_id 字段供 QueryResultTable 使用
        
        return jsonify({
            "success": True,
            "fields": fields,
            "columns": columns,
            "migration_note": "推荐使用 /api/config/search_result_fields/students 获取全局统一配置"
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": f"视力查询结果配置加载失败: {str(e)}"
        }), 500

@config_api.route('/history_fields/vision', methods=['GET'])
def get_vision_history_fields_config():
    """获取视力历史记录表字段配置（全局唯一配置驱动）"""
    try:
        config_manager = ConfigManager()
        history_fields = config_manager.get_vision_history_fields_config()
        return jsonify({
            "success": True,
            "fields": history_fields
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": f"视力历史记录字段配置加载失败: {str(e)}"
        }), 500

@config_api.route('/vision_export_config', methods=['GET'])
def get_vision_export_config():
    """获取视力模块导出配置（Excel和PDF格式配置）"""
    try:
        config_manager = ConfigManager()
        export_config = config_manager.get_registry_config("VISION_EXPORT_CONFIG", {})
        return jsonify({
            "success": True,
            "config": export_config
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": f"视力导出配置加载失败: {str(e)}"
        }), 500

@config_api.route('/vision_form_fields', methods=['GET'])
def get_vision_form_fields_config():
    """获取视力录入表单字段配置（全局唯一配置驱动）"""
    try:
        config_manager = ConfigManager()
        vision_config = config_manager.get_vision_records_config()
        form_fields = vision_config.get('form_fields', [])
        return jsonify({
            "success": True,
            "fields": form_fields
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": f"视力表单字段配置加载失败: {str(e)}"
        }), 500

@config_api.route('/vision/records', methods=['GET'])
def get_vision_records_config():
    """
    获取视力记录模块完整配置（使用ConfigManager动态生成）
    
    🔧 架构规范注释：
    - 必须包含 api_config 配置，前端架构合规性检查要求
    - 所有配置必须来自 constants_v2.py 的统一配置源
    - 不能硬编码任何配置项，必须使用 ConfigManager 动态获取
    - 配置结构必须符合前端组件的期望格式
    """
    try:
        config_manager = ConfigManager()
        
        # 🔧 重要：前端必需的配置项，缺一不可
        vision_config = {
            # 查询和表格相关配置（前端FixedQueryArea和QueryResultTable组件使用）
            "query_fields": config_manager.get_query_area_field_configs(),
            "table_fields": config_manager.get_table_fields_config("vision_records"),
            "history_fields": config_manager.get_table_fields_config("vision_records"),
            "search_result_fields": config_manager.get_table_fields_config("vision_records"),
            
            # ✅ 新增：表单字段配置（前端表单组件使用）
            "form_fields": config_manager.get_vision_form_fields_config(),
            
            # 全局选项配置（下拉框等前端控件使用）
            "global_options": getattr(config_manager.constants_v2, 'GLOBAL_OPTIONS_CONFIG', {}),
            
            # 验证规则配置（前端表单验证使用）
            "validation_rules": config_manager.get_data_validation_patterns(),
            "numeric_ranges": config_manager.get_numeric_validation_ranges(),
            
            # 🔧 关键：API端点配置（前端架构合规性检查必需）
            # 这个配置决定了前端如何调用后端API，缺失会导致架构检查失败
            "api_config": config_manager.get_config("VISION_API_CONFIG", {}),
            
            # ✅ 新增：前端配置（字段标签等）
            "frontend_config": {
                "field_labels": config_manager.get_vision_field_labels()
            }
        }
        
        return jsonify({
            "success": True,
            "config": vision_config
        })
        
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            "success": False,
            "error": f"视力记录配置加载失败: {str(e)}"
        }), 500

@config_api.route('/logs', methods=['GET'])
def get_log_config():
    """获取日志前端配置"""
    try:
        from backend.services.unified_log_service import log_service
        response_data, status_code = log_service.get_log_config_response()
        return jsonify(response_data), status_code
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            "success": False,
            "error": f"日志配置加载失败: {str(e)}"
        }), 500

# =================================================================
# 干预模块配置路由（参考随访和视力模块标准）
# =================================================================

@config_api.route('/history_fields/intervention', methods=['GET'])
def get_intervention_history_fields_config():
    """获取干预模块的历史记录字段配置"""
    try:
        config_manager = ConfigManager()
        fields = config_manager.get_intervention_history_fields()
        return jsonify({
            "success": True,
            "fields": fields
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": f"干预历史记录配置加载失败: {str(e)}"
        }), 500

@config_api.route('/intervention/records', methods=['GET'])
def get_intervention_records_config():
    """获取干预记录完整配置，支持简化模式供小程序使用"""
    try:
        config_manager = ConfigManager()
        
        # 检查是否为简化模式（小程序使用）
        scope = request.args.get('scope', 'full')
        
        if scope == 'simple':
            # 简化模式：只返回小程序需要的基础配置
            intervention_types = config_manager.get_intervention_types()
            return jsonify({
                "success": True,
                "data": {
                    "intervention_types": intervention_types
                },
                "message": "获取干预配置成功"
            })
        
        # 完整模式：PC端需要的所有配置
        # 查询区字段配置（与视力模块保持一致）
        query_fields = config_manager.get_intervention_query_fields()
        
        # 学生查询结果表格字段配置
        search_result_fields = config_manager.get_intervention_search_result_fields()
        
        # 历史记录表格字段配置
        history_fields = config_manager.get_intervention_history_fields()
        
        # 表单字段配置
        form_fields = config_manager.get_intervention_form_fields()
        
        # 干预类型和选项配置
        intervention_types = config_manager.get_intervention_types()
        select_options = config_manager.get_intervention_select_options()
        multi_select_options = config_manager.get_intervention_multi_select_options()
        
        # 级联下拉框配置
        intervention_specific_options = config_manager.get_config("INTERVENTION_SPECIFIC_OPTIONS", {})
        
        # 干预方式配置映射
        intervention_config_map = config_manager.get_intervention_type_config_map()
        
        # 验证规则、默认值、消息配置
        validation_rules = config_manager.get_intervention_api_validation_config()
        defaults = config_manager.get_intervention_api_defaults()
        messages = config_manager.get_intervention_api_messages()
        
        # 字段显示名映射
        field_display_mapping = config_manager.get_config("FIELD_DISPLAY_MAPPING", {})
        
        return jsonify({
            "success": True,
            "config": {
                # 查询和表格配置
                "query_fields": query_fields,
                "search_result_fields": search_result_fields,
                "history_fields": history_fields,
                "form_fields": form_fields,
                
                # 干预类型和选项配置
                "intervention_types": intervention_types,
                "select_options": select_options,
                "multi_select_options": multi_select_options,
                "intervention_specific_options": intervention_specific_options,
                "intervention_config_map": intervention_config_map,
                
                # 验证和消息配置
                "validation_rules": validation_rules,
                "defaults": defaults,
                "messages": messages,
                "field_display_mapping": field_display_mapping
            }
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": f"干预记录配置加载失败: {str(e)}"
        }), 500

@config_api.route('/query_fields/student', methods=['GET'])
def get_student_archive_query_fields_config():
    """获取学生档案模块的查询区字段配置，供前端FixedQueryArea组件使用"""
    try:
        config_manager = ConfigManager()
        fields = config_manager.get_student_archive_query_fields()  # [{field, display_name, input_type, options, ...}, ...]
        return jsonify({
            "success": True,
            "fields": fields
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": f"学生档案查询区配置加载失败: {str(e)}"
        }), 500

@config_api.route('/student_archive_result_fields', methods=['GET'])
def get_student_archive_result_fields():
    """获取学生档案模块主表（查询结果表头）配置"""
    try:
        config_manager = ConfigManager()
        result = config_manager.build_student_archive_search_result_fields()
        
        # 🔧 新增：添加操作列配置
        result.append({
            "field": "actions",
            "display_name": "操作",
            "type": "actions",
            "buttons": ["查看档案", "日志"]
        })
        
        return jsonify({
            "success": True,
            "fields": result
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": f"学生档案主表配置加载失败: {str(e)}"
        }), 500

@config_api.route('/search_result_fields/student_archive', methods=['GET'])
def get_student_archive_search_result_fields_config():
    """
    获取学生档案模块查询结果表格字段配置（QueryResultTable组件专用）
    
    此端点为QueryResultTable组件提供标准化的字段配置接口
    """
    try:
        config_manager = ConfigManager()
        result = config_manager.build_student_archive_search_result_fields()
        
        return jsonify({
            "success": True,
            "fields": result
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": f"学生档案查询结果字段配置加载失败: {str(e)}"
        }), 500

@config_api.route('/options/<option_key>', methods=['GET'])
def get_options_by_key(option_key):
    """
    获取指定的选项配置
    
    此端点用于FixedQueryArea组件动态加载下拉选项
    支持从GLOBAL_OPTIONS_CONFIG获取各种选项配置
    """
    try:
        from backend.config.constants_v2 import GLOBAL_OPTIONS_CONFIG
        
        if option_key not in GLOBAL_OPTIONS_CONFIG:
            return jsonify({
                "success": False,
                "error": f"选项配置 {option_key} 不存在"
            }), 404
        
        options = GLOBAL_OPTIONS_CONFIG[option_key]
        
        return jsonify({
            "success": True,
            "options": options
        })
        
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            "success": False,
            "error": f"获取选项配置失败: {str(e)}"
        }), 500

@config_api.route('/default-columns', methods=['GET'])
def get_default_columns_config():
    """获取查询结果默认显示列配置"""
    try:
        config_manager = ConfigManager()
        config = config_manager.get_config("QUERY_DEFAULT_DISPLAY_COLUMNS")
        
        # 🔧 简化：直接返回原始配置，让前端处理
        return jsonify({
            'success': True,
            'config': config,
            'version': 'v2.0'
        })
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

# =================================================================
# 统计分析模块配置路由（统一配置驱动接口）
# =================================================================

@config_api.route('/analysis/fixed_metrics', methods=['GET'])
def get_analysis_fixed_metrics():
    """获取统计分析固定指标配置"""
    try:
        config_manager = ConfigManager()
        fixed_metrics = config_manager.get_config("FIXED_METRICS", [])
        
        return jsonify({
            "success": True,
            "metrics": fixed_metrics
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": f"统计分析固定指标配置加载失败: {str(e)}"
        }), 500

@config_api.route('/analysis/chart_colors', methods=['GET'])
def get_analysis_chart_colors():
    """获取统计分析图表颜色配置"""
    try:
        config_manager = ConfigManager()
        chart_colors = config_manager.get_config("ANALYSIS_CHART_COLORS", {})
        
        return jsonify({
            "success": True,
            "config": chart_colors
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": f"统计分析图表颜色配置加载失败: {str(e)}"
        }), 500

@config_api.route('/analysis/templates', methods=['GET'])
def get_analysis_templates():
    """获取统计分析模板配置"""
    try:
        config_manager = ConfigManager()
        template_config = config_manager.get_config("ANALYSIS_TEMPLATE_CONFIG", {})
        
        return jsonify({
            "success": True,
            "templates": template_config
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": f"统计分析模板配置加载失败: {str(e)}"
        }), 500

@config_api.route('/analysis/field_display_name/<field_name>', methods=['GET'])
def get_analysis_field_display_name(field_name):
    """获取字段的显示名称（从全局字段配置获取）"""
    try:
        config_manager = ConfigManager()
        display_name = config_manager.get_analysis_field_display_name(field_name)
        
        return jsonify({
            "success": True,
            "field": field_name,
            "display_name": display_name
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": f"字段显示名称获取失败: {str(e)}"
        }), 500

@config_api.route('/analysis/complete_config', methods=['GET'])
def get_analysis_complete_config():
    """获取统计分析模块完整配置（统一配置驱动）"""
    try:
        config_manager = ConfigManager()
        analysis_config = config_manager.build_analysis_complete_config()
        
        return jsonify({
            "success": True,
            "config": analysis_config
        })
        
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            "success": False,
            "error": f"统计分析完整配置加载失败: {str(e)}"
        }), 500

@config_api.route('/search_result_fields/followup', methods=['GET'])
def get_followup_search_result_fields_config():
    """
    获取随访模块学生查询结果表格字段配置（全局唯一配置驱动）
    
    此端点参照视力模块结构，为随访模块提供专用的查询结果表格配置
    """
    try:
        config_manager = ConfigManager()
        
        # 从CONFIG_REGISTRY获取随访搜索结果字段配置
        followup_result_fields = config_manager.build_followup_result_fields()
        
        # 添加随访模块特定的操作列配置
        action_field = {
            "field": "actions",
            "display_name": "操作",
            "input_type": "actions",
            "buttons": ["查询", "录入"]  # 随访模块专用操作按钮
        }
        followup_result_fields.append(action_field)
        
        # 提取列名用于查询
        columns = [field["field"] for field in followup_result_fields if field["field"] != "actions"]
        columns.append("id")  # 确保包含ID字段
        
        return jsonify({
            "success": True,
            "fields": followup_result_fields,
            "columns": columns
        })
        
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            "success": False,
            "error": f"随访搜索结果字段配置加载失败: {str(e)}"
        }), 500

@config_api.route('/search_result_fields/intervention', methods=['GET'])
def get_intervention_search_result_fields_config():
    """
    获取干预记录模块学生查询结果表格字段配置（全局唯一配置驱动）
    
    此端点参照视力模块结构，为干预记录模块提供专用的查询结果表格配置
    """
    try:
        config_manager = ConfigManager()
        
        # 从CONFIG_REGISTRY获取干预搜索结果字段配置
        intervention_result_fields = config_manager.get_intervention_search_result_fields()
        
        # 添加干预模块特定的操作列配置
        action_field = {
            "field": "actions",
            "display_name": "操作",
            "input_type": "actions",
            "buttons": ["查询", "录入"]  # 干预模块专用操作按钮
        }
        intervention_result_fields.append(action_field)
        
        # 提取列名用于查询
        columns = [field["field"] for field in intervention_result_fields if field["field"] != "actions"]
        columns.append("id")  # 确保包含ID字段
        
        return jsonify({
            "success": True,
            "fields": intervention_result_fields,
            "columns": columns
        })
        
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            "success": False,
            "error": f"干预搜索结果字段配置加载失败: {str(e)}"
        }), 500

@config_api.route('/history_fields/followup', methods=['GET'])
def get_followup_history_fields_config():
    """获取随访历史表格字段配置"""
    try:
        config_manager = ConfigManager()
        fields = config_manager.build_followup_history_fields()
        return jsonify({
            "success": True,
            "fields": fields
        })
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            "success": False,
            "error": f"随访历史表配置加载失败: {str(e)}"
        }), 500

# ==================== 组合查询配置API ====================

@config_api.route('/combo_query/field_config', methods=['GET'])
def get_combo_query_field_config():
    """
    获取组合查询字段配置
    
    返回组合查询组件所需的所有字段配置，包括：
    - 字段标签
    - 字段类型
    - 选项数据
    - 所属数据表
    """
    try:
        config_manager = ConfigManager()
        field_config = config_manager.get_combo_query_field_config()
        
        return jsonify({
            "success": True,
            "field_config": field_config
        })
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            "success": False,
            "error": f"组合查询字段配置加载失败: {str(e)}"
        }), 500

@config_api.route('/combo_query/role_options', methods=['GET'])
def get_combo_query_role_options():
    """
    获取组合查询角色选项配置
    
    返回角色选择下拉框的选项，包括：
    - 统计指标
    - 分组
    - 筛选
    """
    try:
        config_manager = ConfigManager()
        role_options = config_manager.get_combo_query_role_options()
        
        return jsonify({
            "success": True,
            "role_options": role_options
        })
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            "success": False,
            "error": f"组合查询角色选项配置加载失败: {str(e)}"
        }), 500

@config_api.route('/combo_query/templates', methods=['GET'])
def get_combo_query_templates():
    """
    获取组合查询模板配置
    
    返回预设的查询模板，包括：
    - 学生基本信息查询
    - 视力分析查询
    - 干预效果查询
    """
    try:
        config_manager = ConfigManager()
        templates = config_manager.get_combo_query_templates()
        
        return jsonify({
            "success": True,
            "templates": templates
        })
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            "success": False,
            "error": f"组合查询模板配置加载失败: {str(e)}"
        }), 500

@config_api.route('/combo_query/component_config', methods=['GET'])
def get_combo_query_component_config():
    """
    获取组合查询组件配置
    
    返回组件的行为配置，包括：
    - 默认模式
    - 功能开关
    - 验证规则
    """
    try:
        config_manager = ConfigManager()
        component_config = config_manager.get_combo_query_component_config()
        
        return jsonify({
            "success": True,
            "component_config": component_config
        })
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            "success": False,
            "error": f"组合查询组件配置加载失败: {str(e)}"
        }), 500

@config_api.route('/combo_query/complete_config', methods=['GET'])
def get_combo_query_complete_config():
    """
    获取组合查询完整配置
    
    一次性返回所有组合查询相关配置，包括：
    - 字段配置
    - 角色选项
    - 查询模板
    - 组件配置
    """
    try:
        config_manager = ConfigManager()
        complete_config = config_manager.build_combo_query_complete_config()
        
        return jsonify({
            "success": True,
            "config": complete_config
        })
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            "success": False,
            "error": f"组合查询完整配置加载失败: {str(e)}"
        }), 500

@config_api.route('/combo_query/field_options/<field_name>', methods=['GET'])
def get_combo_query_field_options(field_name):
    """
    获取指定字段的选项列表
    
    Args:
        field_name: 字段名称
        
    Returns:
        字段的选项列表
    """
    try:
        config_manager = ConfigManager()
        options = config_manager.get_combo_query_field_options(field_name)
        
        return jsonify({
            "success": True,
            "field_name": field_name,
            "options": options
        })
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            "success": False,
            "error": f"字段选项加载失败: {str(e)}"
        }), 500

@config_api.route('/combo_query/validate_field/<field_name>', methods=['GET'])
def validate_combo_query_field(field_name):
    """
    验证组合查询字段是否有效
    
    Args:
        field_name: 字段名称
        
    Returns:
        字段是否有效
    """
    try:
        config_manager = ConfigManager()
        is_valid = config_manager.validate_combo_query_field(field_name)
        
        return jsonify({
            "success": True,
            "field_name": field_name,
            "is_valid": is_valid
        })
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            "success": False,
            "error": f"字段验证失败: {str(e)}"
        }), 500

@config_api.route("/report-template-options", methods=["GET"])
def get_report_template_options():
    """
    获取报表模板选项配置
    ---
    tags:
      - Config
    responses:
      200:
        description: 报表模板选项配置
    """
    try:
        config_manager = ConfigManager()
        template_options = config_manager.get_report_template_options()
        
        return jsonify({
            "success": True,
            "data": template_options,
            "message": "获取报表模板选项配置成功"
        })
    except Exception as e:
        current_app.logger.error(f"获取报表模板选项配置失败: {str(e)}", exc_info=True)
        return jsonify({
            "success": False,
            "data": None,
            "message": f"获取报表模板选项配置失败: {str(e)}"
        }), 500

@config_api.route("/report-role-field-config", methods=["GET"])
def get_report_role_field_config():
    """
    获取报表角色化字段配置
    ---
    tags:
      - Config
    responses:
      200:
        description: 报表角色化字段配置
    """
    try:
        config_manager = ConfigManager()
        role_config = config_manager.get_report_role_field_config()
        # 增加顺序数组
        metric_field_order = list(role_config.get("metric_fields", {}).keys())
        group_field_order = list(role_config.get("group_fields", {}).keys())
        filter_field_order = list(role_config.get("filter_fields", {}).keys())
        # 返回时带上顺序
        return jsonify({
            "success": True,
            "data": {
                **role_config,
                "metric_field_order": metric_field_order,
                "group_field_order": group_field_order,
                "filter_field_order": filter_field_order,
            },
            "message": "获取报表角色化字段配置成功"
        })
    except Exception as e:
        current_app.logger.error(f"获取报表角色化字段配置失败: {str(e)}", exc_info=True)
        return jsonify({
            "success": False,
            "data": None,
            "message": f"获取报表角色化字段配置失败: {str(e)}"
        }), 500

@config_api.route("/report-fields-by-role/<role>", methods=["GET"])
def get_report_fields_by_role(role):
    """
    根据角色获取报表字段配置
    ---
    tags:
      - Config
    parameters:
      - name: role
        in: path
        required: true
        schema:
          type: string
          enum: [metric, group, filter]
    responses:
      200:
        description: 指定角色的字段配置
    """
    try:
        config_manager = ConfigManager()
        fields = config_manager.get_report_fields_by_role(role)
        
        return jsonify({
            "success": True,
            "data": fields,
            "message": f"获取{role}角色字段配置成功"
        })
    except Exception as e:
        current_app.logger.error(f"获取{role}角色字段配置失败: {str(e)}", exc_info=True)
        return jsonify({
            "success": False,
            "data": None,
            "message": f"获取{role}角色字段配置失败: {str(e)}"
        }), 500

@config_api.route("/report-role-options", methods=["GET"])
def get_report_role_options():
    """
    获取报表角色选项配置
    ---
    tags:
      - Config
    responses:
      200:
        description: 报表角色选项配置
    """
    try:
        config_manager = ConfigManager()
        role_options = config_manager.get_report_role_options()
        
        return jsonify({
            "success": True,
            "data": role_options,
            "message": "获取报表角色选项配置成功"
        })
    except Exception as e:
        current_app.logger.error(f"获取报表角色选项配置失败: {str(e)}", exc_info=True)
        return jsonify({
            "success": False,
            "data": None,
            "message": f"获取报表角色选项配置失败: {str(e)}"
        }), 500

@config_api.route("/report-field-options/<field_name>", methods=["GET"])
def get_report_field_options(field_name):
    """
    获取报表字段的选项列表
    ---
    tags:
      - Config
    parameters:
      - name: field_name
        in: path
        required: true
        schema:
          type: string
    responses:
      200:
        description: 字段选项列表
    """
    try:
        config_manager = ConfigManager()
        options = config_manager.get_report_field_options(field_name)
        
        return jsonify({
            "success": True,
            "data": options,
            "message": f"获取字段{field_name}选项成功"
        })
    except Exception as e:
        current_app.logger.error(f"获取字段{field_name}选项失败: {str(e)}", exc_info=True)
        return jsonify({
            "success": False,
            "data": [],
            "message": f"获取字段{field_name}选项失败: {str(e)}"
        }), 500

@config_api.route("/report-field-info/<field_name>", methods=["GET"])
def get_report_field_info(field_name):
    """
    获取报表字段的完整信息
    ---
    tags:
      - Config
    parameters:
      - name: field_name
        in: path
        required: true
        schema:
          type: string
      - name: role
        in: query
        required: false
        schema:
          type: string
          enum: [metric, group, filter]
    responses:
      200:
        description: 字段完整信息
    """
    try:
        config_manager = ConfigManager()
        role = request.args.get('role')
        field_info = config_manager.get_report_field_info(field_name, role)
        
        if field_info:
            return jsonify({
                "success": True,
                "data": field_info,
                "message": f"获取字段{field_name}信息成功"
            })
        else:
            return jsonify({
                "success": False,
                "data": None,
                "message": f"字段{field_name}不存在"
            }), 404
    except Exception as e:
        current_app.logger.error(f"获取字段{field_name}信息失败: {str(e)}", exc_info=True)
        return jsonify({
            "success": False,
            "data": None,
            "message": f"获取字段{field_name}信息失败: {str(e)}"
        }), 500



